package com.maistars.spider.service.render;

import com.maistars.spider.common.constants.RenderEngineType;
import com.maistars.spider.common.exception.TopicSpiderException;
import com.maistars.spider.service.domain.render.PageRequest;
import com.maistars.spider.service.domain.render.PageResponse;
import com.maistars.spider.service.render.handler.HtmlHandler;
import com.maistars.spider.service.render.handler.impl.BaseHrefHtmlHandler;
import com.maistars.spider.service.render.handler.impl.DoubleSlashHtmlHandler;
import com.maistars.spider.service.render.handler.impl.CleanHtmlHandler;
import com.maistars.spider.service.render.handler.impl.RootHtmlHandler;
import com.maistars.spider.service.render.impl.SeleniumRender;
import com.maistars.spider.service.render.impl.SimpleRender;

import java.util.HashMap;
import java.util.Map;

/**
 * @author dhr
 * @date 2021/11/21 上午12:16
 */
public class RenderService {

    private static Map<RenderEngineType,PageRender> renders = new HashMap<>();

    static {
        initRenderEngine();
    }

    private static void initRenderEngine() {
        renders.put(RenderEngineType.SIMPLE,new SimpleRender());
        renders.put(RenderEngineType.SELENIUM,new SeleniumRender());
    }

    public PageResponse renderPage(RenderEngineType renderEngineType, PageRequest pageRequest) throws TopicSpiderException {
        PageRender pageRender = renders.get(renderEngineType);
        return pageRender.renderPage(pageRequest);
    }

    public HtmlHandler getDefaultHtmlHandler() {
        Map<String,String> context = new HashMap<>();
        HtmlHandler rootHtmlHandler = new RootHtmlHandler(context);
        HtmlHandler baseHrefHtmlHandler = new BaseHrefHtmlHandler(context);
        HtmlHandler doubleSlashHtmlHandler = new DoubleSlashHtmlHandler(context);
        HtmlHandler removeJsHtmlHandler = new CleanHtmlHandler(context);
        rootHtmlHandler.setNextHandler(removeJsHtmlHandler);
        removeJsHtmlHandler.setNextHandler(baseHrefHtmlHandler);
        baseHrefHtmlHandler.setNextHandler(doubleSlashHtmlHandler);
        return rootHtmlHandler;
    }

}
